package cn.smbms.controller.user;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.role.RoleServiceImpl;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;

	/**
	 * 到登陆页面
	 * 
	 * @return SeanAstin
	 */
	@RequestMapping(value = "/login.html")
	public String login() {
		return "login";
	}

	/**
	 * 登陆处理
	 * 
	 * @param userCode
	 *            用户名
	 * @param userPassword
	 *            密码
	 * @param session
	 * @return 主页面
	 */
	@RequestMapping(value = "/doLogin.html", method = RequestMethod.POST)
	public String doLogin(String userCode, String userPassword, HttpSession session) {
		User user = userService.login(userCode, userPassword);
		if (null != user) {
			session.setAttribute(Constants.USER_SESSION, user);
			return "redirect:/user/main.html";
		} else {
			return "login";
		}
	}

	/**
	 * 主页面
	 * 
	 * @return 主页视图
	 */
	@RequestMapping(value = "/main.html")
	public String main() {
		return "frame";
	}

	/**
	 * 用户列表页 分页
	 * 
	 * @param queryname
	 *            名称
	 * @param queryUserRole
	 *            用户角色
	 * @param pageIndex
	 *            页码
	 * @param model
	 *            模型
	 * @return 用户列表视图
	 */
	@RequestMapping(value = "/userList.html")
	public String userList(@RequestParam(value = "queryname", required = false) String queryname,
			@RequestParam(value = "queryUserRole", required = false) String queryUserRole,
			@RequestParam(value = "pageIndex", required = false) String pageIndex, Model model) {
		if (queryname == null) {
			queryname = "";
		}
		int _queryUserRole = 0;
		if (queryUserRole != null && !queryUserRole.equals("")) {
			_queryUserRole = Integer.parseInt(queryUserRole);
		}

		List<User> userList = null;
		// 设置页面容量
		int pageSize = Constants.pageSize;
		// 当前页码
		int currentPageNo = 1;
		/**
		 * http://localhost:8090/SMBMS/userlist.do ----queryUserName --NULL
		 * http://localhost:8090/SMBMS/userlist.do?queryname= --queryUserName
		 * ---""
		 */
		System.out.println("queryUserName servlet--------" + queryname);
		System.out.println("queryUserRole servlet--------" + queryUserRole);
		System.out.println("query pageIndex--------- > " + pageIndex);

		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				return "error";
			}
		}
		// 总数量（表）
		int totalCount = userService.getUserCount(queryname, _queryUserRole);
		// 总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);

		int totalPageCount = pages.getTotalPageCount();

		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}

		userList = userService.getUserList(queryname, _queryUserRole, currentPageNo, pageSize);
		model.addAttribute("userList", userList);
		List<Role> roleList = null;
		RoleService roleService = new RoleServiceImpl();
		roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryname);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "userlist";
	}

	/**
	 * 新增用户
	 * 
	 * @param user
	 *            用户模型
	 * @return 新增用户视图
	 */
	@RequestMapping(value = "/userAdd.html", method = RequestMethod.GET)
	public String userAdd(@ModelAttribute("user") User user) {
		return "useradd";
	}

	/**
	 * 新增用户
	 * 
	 * @param user
	 *            用户对象
	 * @param session
	 *            获取当前登陆用户
	 * @return 用户列表
	 */
	@RequestMapping(value = "/saveUser.html", method = RequestMethod.POST)
	public String saveUser(User user, HttpServletRequest request, HttpSession session,
			@RequestParam(value = "a_idPicPath", required = false) MultipartFile attch) {
		String idPicPath = null;
		if (!attch.isEmpty()) {
			String path = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadfiles");
			String oldFileName = attch.getOriginalFilename();
			String prefix = FilenameUtils.getExtension(oldFileName);

			int filesize = 500000;
			if (attch.getSize() > filesize) {
				request.setAttribute("uploadFileError", "上传大小不能超过500KB");
				return "useradd";
			} else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")) {
				String fileName = System.currentTimeMillis() + RandomUtils.nextInt() + "_Personnal.jpg";
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}

				try {
					attch.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("uploadFileError", "* 上传失败");
					return "useradd";
				}
				idPicPath = path + File.separator + fileName;
			} else {
				request.setAttribute("uploadFileError", "*  格式不正确");
				return "useradd";
			}
		}
		user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		user.setIdPicPath(idPicPath);
		if (userService.add(user)) {
			return "redirect:/user/userList.html";
		} else {
			return "useradd";
		}
	}

	/**
	 * 新增用户
	 * 
	 * @param user
	 *            用户模型
	 * @return 新增用户视图
	 */
	@RequestMapping(value = "/userAdd2.html", method = RequestMethod.GET)
	public String userAdd2(@ModelAttribute("user") User user) {
		return "useradd2";
	}

	/**
	 * 新增用户
	 * 
	 * @param user
	 *            用户对象
	 * @param session
	 *            获取当前登陆用户
	 * @return 用户列表
	 */
	@RequestMapping(value = "/userAdd2.html", method = RequestMethod.POST)
	public String saveUser2(@Valid User user, BindingResult bindingResult, HttpSession session) {
		user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		if (bindingResult.hasErrors())
			return "useradd2";
		if (userService.add(user)) {
			return "redirect:/user/userList.html";
		} else {
			return "useradd2";
		}
	}

	// 查看用户ById
	/*
	 * @RequestMapping(value = "/view/{id}", method = RequestMethod.GET) public
	 * String view(@PathVariable String id, Model model) { User user =
	 * userService.getUserById(id); model.addAttribute("user", user); return
	 * "userview"; }
	 */

	// 查看用户ById ajax版
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	@ResponseBody
	public User view2(@RequestParam String id) {
		User user = userService.getUserById(id);
		// 把user对象转成json字符串 ！aplication/json text/html
		return user;
	}

	@RequestMapping(value = "/modifyUser.html", method = RequestMethod.GET)
	public String modifyUser(@RequestParam String uid, Model model) {
		User user = userService.getUserById(uid);
		model.addAttribute("user", user);
		return "usermodify";
	}

	@RequestMapping(value = "/updUser.html", method = RequestMethod.POST)
	public String updUser(User user, HttpSession session) {
		user.setModifyBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
		user.setModifyDate(new Date());
		if (userService.modify(user)) {
			return "redirect:/user/userList.html";
		} else {
			return "usermodify";
		}
	}

	@RequestMapping(value = "/ucexist.html")
	@ResponseBody
	public Object userCodeIsExit(@RequestParam String userCode) {
		System.out.println("通过Ajax进来的，userCode是否存在！！！");
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if (StringUtils.isNullOrEmpty(userCode)) {
			resultMap.put("userCode", "exist");
		} else {
			User user = userService.selectUserCodeExist(userCode);
			if (null != user) {
				resultMap.put("userCode", "exist");
			} else {
				resultMap.put("userCode", "noexist");
			}
		} // {"userCode":"exist"}
		return JSONArray.toJSONString(resultMap);
	}

}
